<script lang="ts" setup>
import { isDark } from '@/utils/is'
import { useAppStore } from '@/store/modules/app'
import { useDesign } from '@/hooks/web/useDesign'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import routerSearch from '@/components/RouterSearch/index.vue'

defineOptions({ name: 'APP' })

const { getPrefixCls } = useDesign()
const prefixCls = getPrefixCls('app')
const appStore = useAppStore()
const currentSize = computed(() => appStore.getCurrentSize)
const greyMode = computed(() => appStore.getGreyMode)
const { wsCache } = useCache()

// 根据浏览器当前主题设置系统主题色
const setDefaultTheme = () => {
  let isDarkTheme = wsCache.get(CACHE_KEY.IS_DARK)
  if (isDarkTheme === null) {
    isDarkTheme = isDark()
  }
  appStore.setIsDark(isDarkTheme)
}
setDefaultTheme()


import { ref } from 'vue';
const statusMessage = ref('准备就绪')
const isSpeaking = ref(false)
const isSupported = ref(false)

const rate = ref(1)
const pitch = ref(1)
const volume = ref(1)


const initAuto=()=>{
   if ('speechSynthesis' in window) {
            isSupported.value = true
            statusMessage.value = '语音功能已启用'
          } else {
            statusMessage.value = '您的浏览器不支持语音合成功能'
          }
}
initAuto()
//k开始播报
const speak = (text='有订单啦') => {
          if (!isSupported.value) {
            statusMessage.value = '浏览器不支持语音功能'
            return
          }
          
          if (isSpeaking.value) {
            statusMessage.value = '语音正在播报中...'
            return
          }
          
          // 停止当前语音
          window.speechSynthesis.cancel()
          // 创建新的语音
          const speech = new SpeechSynthesisUtterance(text)
          speech.rate = rate.value
          speech.pitch = pitch.value
          speech.volume = volume.value
          speech.lang = 'zh-CN'
          
          // 事件监听
          speech.onstart = () => {
            isSpeaking.value = true
            statusMessage.value = '语音播报中...'
          }
          
          speech.onend = () => {
            isSpeaking.value = false
            statusMessage.value = '播报完成'
          }
          
          speech.onerror = (event) => {
            isSpeaking.value = false
            statusMessage.value = '播报出错: ' + event.error
          }
          
          // 开始播报
          window.speechSynthesis.speak(speech)
  }
  // 停止播报
const stop = () => {
    if (window.speechSynthesis.speaking) {
      window.speechSynthesis.cancel()
      isSpeaking.value = false
      statusMessage.value = '已停止播报'
    }
}
import { useWebSocket } from '@vueuse/core'
import { getRefreshToken } from '@/utils/auth'


const message = useMessage() // 消息弹窗
const server = ref(
  (import.meta.env.VITE_BASE_URL + '/infra/ws').replace('http', 'ws') +
    '?token=' +
    getRefreshToken() // 使用 getRefreshToken() 方法，而不使用 getAccessToken() 方法的原因：WebSocket 无法方便的刷新访问令牌
) // WebSocket 服务地址
const getIsOpen = computed(() => status.value === 'OPEN') // WebSocket 连接是否打开

/** 发起 WebSocket 连接 */
const { status, data, send, close, open } = useWebSocket(server.value, {
  autoReconnect: true,
  heartbeat: true
})

/** 监听接收到的数据 */

watchEffect(() => {
  if (!data.value) {
    return
  }
  try {
    // 1. 收到心跳
    if (data.value === 'pong') {
      // state.recordList.push({
      //   text: '【心跳】',
      //   time: new Date().getTime()
      // })
      return
    }

    // 2.1 解析 type 消息类型
    const jsonMessage = JSON.parse(data.value)
    const type = jsonMessage.type
    const content = JSON.parse(jsonMessage.content)
    if (!type) {
      message.error('未知的消息类型：' + data.value)
      return
    }
    // 2.2 消息类型：demo-message-receive
    if (type === 'complete_pay_order') {
      speak('有订单啦')
      return
    }

  } catch (error) {
    message.error('处理消息发生异常：' + data.value)
    console.error(error)
  }
})

</script>
<template>
  <ConfigGlobal :size="currentSize">
    <RouterView :class="greyMode ? `${prefixCls}-grey-mode` : ''" />
    <routerSearch />
  </ConfigGlobal>
</template>
<style lang="scss">
$prefix-cls: #{$namespace}-app;

.size {
  width: 100%;
  height: 100%;
}

html,
body {
  @extend .size;

  padding: 0 !important;
  margin: 0;
  overflow: hidden;

  #app {
    @extend .size;
  }
}

.#{$prefix-cls}-grey-mode {
  filter: grayscale(100%);
}
</style>
